<template>
  <view class="page">
    <view class="nav-box">
      <view
        class="btn"
        @click="goHome"
        :style="`--icon: url(${base_url + '/static/goHome.svg'});`"
      ></view>
      <view
        class="btn"
        @click="goBack"
        :style="`--icon: url(${base_url + '/static/goBack.svg'});`"
      ></view>
    </view>
    <view class="nav-bar">
      <view class="title">个人信息</view>
    </view>
    <view class="content-scroll">
      <view class="item">
        <view class="name">头像</view>
        <view class="middle">
          <view class="head-portrait-container">
            <view class="btn-change" @click="handleChangeAvatar">更改</view>
            <image :src="avatar" mode="aspectFill" />
          </view>
        </view>
        <view class="content"></view>
      </view>
      <view class="item">
        <view class="name">姓名</view>
        <input class="content" v-model="username" />
      </view>
      <picker mode="selector" :range="['男', '女']" @change="handleSelectSex">
        <view class="item">
          <view class="name">性别</view>
          <view class="content">
            <view
              v-show="sex.length"
              class="sex"
              :style="`--bg: ${
                sex == '男' ? 'rgb(0, 170, 255)' : 'rgb(255, 170, 200)'
              }; --img: url(${
                base_url +
                (sex == '男' ? '/static/boy-icon.svg' : '/static/girl-icon.svg')
              }); --bgs: ${sex == '男' ? '40%' : '50%'};`"
            ></view>
          </view>
        </view>
      </picker>
      <view class="item">
        <view class="name">学校</view>
        <input class="content" v-model="college" />
      </view>
      <view class="item">
        <view class="name">学院</view>
        <input class="content" v-model="subCollege" />
      </view>
      <view class="item">
        <view class="name">专业</view>
        <input class="content" v-model="major" />
      </view>
      <view class="item">
        <view class="name">年级</view>
        <input class="content" v-model="grade" />
      </view>
      <view class="item">
        <view class="header">
          <view class="name">个人简介</view>
          <textarea
            class="desc"
            v-model="userDescription"
            :maxlength="descMaxLength"
          />
          <view class="limit">{{ descLength }}/{{ descMaxLength }}</view>
        </view>
        <view class="content"></view>
      </view>
      <view class="btn-save-container">
        <view :class="{ 'btn-save': true, active: isChange }" @click="handleChangeInfo">保存修改</view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import { user } from "../../service/user";
import { base_url } from "../../api/config";
import { imageUrl2DataUrl } from "../../utils/base64";

const avatar = ref("");

async function updateAvatar(dataurl) {
  try {
    const res = await user.changeUserAvatar(dataurl);
    if (res.code === 200) {
      uni.showToast({
        title: "头像更新成功",
        icon: "success",
        duration: 2000,
      });
    } else {
      uni.showToast({
        title: "头像更新失败",
        icon: "none",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("更新头像时发生错误：", error);
  }
}

let originalUsername = ref("");
let originalSex = ref("");
let originalCollege = ref("");
let originalSubCollege = ref("");
let originalMajor = ref("");
let originalGrade = ref("");
let originalUserDescription = ref("");

const username = ref("陈树洞");
const sex = ref("男");
const college = ref("广东东软学院");
const subCollege = ref("计算机学院");
const major = ref("软件工程");
const grade = ref("大一");
const userDescription = ref("这是一个个人简介，暂时没有内容。");

const handleSelectSex = (e) => {
  const selectedIndex = e.detail.value;
  const selectedSex = selectedIndex === "0" ? "男" : "女";
  sex.value = selectedSex;
};

const descMaxLength = 100;
const descLength = computed(() => {
  return userDescription.value.length;
});

const isChange = computed(() => {
  return (
    username.value !== originalUsername.value ||
    sex.value !== originalSex.value ||
    college.value !== originalCollege.value ||
    subCollege.value !== originalSubCollege.value ||
    major.value !== originalMajor.value ||
    grade.value !== originalGrade.value ||
    userDescription.value !== originalUserDescription.value
  );
});

function goHome() {
  uni.reLaunch({
    url: "/pages/main/main",
  });
}

function goBack() {
  uni.navigateBack();
}

const handleChangeAvatar = () => {
  try {
    uni.chooseMedia({
      count: 1, // 选择图片的数量
      mediaType: ["image"], // 只选
      sourceType: ["album"], // 来源：相册
      sizeType: ["original", "compressed"], // 图片大小：原图和压缩图
      async success(res) {
        const imageUrl = res.tempFiles[0].tempFilePath;
        const imageDataurl = await imageUrl2DataUrl(imageUrl); // 处理图片为base64 dataurl 格式
        avatar.value = imageDataurl; // 设置图片的dataurl
        updateAvatar(imageDataurl); // 更新头像
      },
      fail(res) {
        throw new Error("选择图片失败", res);
      },
    });
  } catch (error) {
    console.error("选择图片时发生错误：", error);
  }
};

const handleChangeInfo = async () => {
  if (!isChange.value) {
    uni.showToast({
      title: "没有修改任何信息",
      icon: "none",
      duration: 2000,
    });
    return;
  }
  
  // 打包新数据
  const newUserInfo = {
    username: username.value,
    sex: sex.value,
    college: college.value,
    subCollege: subCollege.value,
    major: major.value,
    grade: grade.value,
    bio: userDescription.value,
  };

  const res = await user.changeUserInfo(newUserInfo);
  if (res.code === 200) {
    uni.showToast({
      title: res.msg,
      icon: "success",
      duration: 2000,
    });
    // 更新数据
    setUserInfo(newUserInfo);
  }
}

function setUserInfo(data) {
  username.value = data.username || "";
  sex.value = data.sex || "";
  college.value = data.college || "";
  subCollege.value = data.subCollege || "";
  major.value = data.major || "";
  grade.value = data.grade || "";
  userDescription.value = data.bio || "";
  originalUsername.value = data.username; // 保存原始用户名
  originalSex.value = data.sex; // 保存原始性别
  originalCollege.value = data.college; // 保存原始学校
  originalSubCollege.value = data.subCollege; // 保存原始学院
  originalMajor.value = data.major; // 保存原始专业
  originalGrade.value = data.grade; // 保存原始年级
  originalUserDescription.value = data.bio; // 保存原始个人简介
}

async function getUserInfo() {
  const data = await user.getUserInfo();
  if (data.avatar) {
    if (data.avatar.startsWith("http")) {
      avatar.value = data.avatar;
    } else {
      avatar.value = base_url + data.avatar;
    }
  }
  setUserInfo(data);
}

async function getPageInfo() {
  getUserInfo();
}
getPageInfo();
</script>

<style scoped lang="less">
.page {
  height: 100vh;
  background-image: linear-gradient(to bottom, rgb(255, 212, 168), #fff);
  position: relative;
  display: flex;
  flex-direction: column;

  .nav-box {
    width: min-content;
    padding: 1vw;
    background-color: rgba(136, 136, 136, 0.4);
    display: flex;
    border-radius: 0 5vw 5vw 0;
    position: absolute;
    top: 15vw;
    left: 0;

    .btn {
      width: 12vw;
      height: 7vw;
      background-image: var(--icon);
      background-position: center;
      background-size: contain;
      background-repeat: no-repeat;
    }
  }

  .nav-bar {
    box-sizing: border-box;
    width: 100%;
    height: 30vw;
    padding-top: 15vw;

    .title {
      position: absolute;
      top: 15vw;
      left: 50%;
      transform: translateX(-50%);
      font-size: 5vw;
    }
  }

  .content-scroll {
    flex: 1;
    background-color: #fff;
    overflow: auto;

    .item {
      display: flex;
      justify-content: space-between;
      padding: 5vw;
      // padding-right: 10vw;
      position: relative;
      border-bottom: 0.1vw solid #d3d3d3;

      .head-portrait-container {
        position: relative;
        --size: 30vw;
        width: var(--size);
        height: var(--size);
        border-radius: 50%;
        background-color: #f0f0f0;
        background-size: cover;

        .btn-change {
          position: absolute;
          bottom: 0;
          right: 0;
          padding: 1vw 2vw;
          background-color: rgba(0, 0, 0, 0.3);
          color: white;
          text-align: center;
          font-size: 3vw;
          border-radius: 3vw;
        }

        image {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }

      .header {
        display: flex;
        flex-direction: column;
        width: 100%;

        .desc {
          min-height: 25vw;
          margin-top: 1vw;
        }
        .limit {
          color: #888;
          font-size: 3vw;
          align-self: flex-end;
        }
      }

      .content {
        font-weight: bold;
        text-align: right;

        .sex {
          width: 6vw;
          height: 4vw;
          background-color: var(--bg);
          background-image: var(--img);
          background-size: var(--bgs);
          background-repeat: no-repeat;
          background-position: center;
          border-radius: 2vw;
        }
      }

      // &::after {
      //   --size: 3vw;
      //   content: "";
      //   display: block;
      //   width: var(--size);
      //   height: var(--size);
      //   border-top: 0.5vw solid #888;
      //   border-right: 0.5vw solid #888;
      //   position: absolute;
      //   top: 50%;
      //   right: 5vw;
      //   transform: translateY(-50%) rotate(45deg);
      // }
    }

    .btn-save-container {
      width: 100%;
      padding: 5vw;
      box-sizing: border-box;
      font-weight: bold;
      .btn-save {
        padding: 3vw;
        border-radius: 5vw;
        background-color: #888888;
        color: white;
        text-align: center;

        &.active {
          background-color: #d4e98c;
          color: black;
        }
      }
    }
  }
}
</style>
